import {
	dev_base_api,
	stage_base_api,
	prod_base_api
} from "@/config.js";
import store from "@/store";
import jwtSign from "@/utils/jwtSign.js";
let baseUrl = '';
const accountInfo = uni.getAccountInfoSync();
if (accountInfo?.miniProgram?.envVersion === 'develop') { //开发版
	baseUrl = dev_base_api;
} else if (accountInfo?.miniProgram?.envVersion === 'trial') { //体验版
	baseUrl = stage_base_api;
} else { //正式版
	baseUrl = prod_base_api;
}

const uniRequest = (url, method, params, type = "jwt", myConfig = {}) => {
	return new Promise((resolve, reject) => {
		let header = {};
		let data = {};
		// 需要加签的
		if (type === "jwt") {
			let Authorization = {
				"uid": store.state.uid,
				"iat": (new Date().getTime() / 1000).toFixed(0),
				"token": store.state.token,
				...params,
			};
			console.log(Authorization);
			Authorization = jwtSign(Authorization);
			header.Authorization = Authorization;
			// 开发版将传参放入data
			data = params;
		}
		uni.request({
			url: baseUrl + url,
			data,
			header,
			method,
			success: (res) => {
				if (res.statusCode === 200) {
					if (res.data.code === 200) {
						resolve(res.data);
					}
					// 令牌错误
					else if (res.data.code === 401) {
						store.dispatch('logout');
						reject(res.data);
					}
					// 报错
					else if (res.data.code === 400) {
						// uni.showToast({
						// 	icon: "error",
						// 	title: res.data.msg,
						// });
						reject(res.data);
					}
					// 其他错误
					else {
						reject(res.data);
					}
				} else {
					uni.showToast({
						icon: "error",
						title: '系统错误',
					})
					reject(res.data);
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: "error",
					title: '系统错误',
				})
				reject(err);
			}
		})
	})
}
export default uniRequest;
